package com.reebake.ideal.message.websocket.core;

import com.reebake.ideal.crypto.util.JwtUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.StringUtils;

import java.security.Principal;

@Slf4j
public class WebSocketChannelInterceptor implements ChannelInterceptor {

	/**
	 * 发送消息到通道前
	 * 
	 * @param message
	 * @param channel
	 * @return
	 */
	@SneakyThrows
	@Override
	public Message<?> preSend(Message<?> message, MessageChannel channel) {
		// 获取连接头信息
		StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

		if (StompCommand.CONNECT.equals(accessor.getCommand())) {
			String userId = null;
			// 获取头中的token
			String bearerToken = accessor.getFirstNativeHeader(HttpHeaders.AUTHORIZATION);
			if (!StringUtils.hasText(bearerToken)) {
				// 会话编号当用户编号
				userId = accessor.getFirstNativeHeader(WebsocketConstants.HEADER_NAME_SESSION_ID);
				if(!StringUtils.hasText(userId)) {
					log.error("没有携带token或会话编号，不允许进行连接.");
					throw new IllegalArgumentException("UNAUTHORIZED");
				}
			}else {
				userId = JwtUtil.getUserId(bearerToken);
			}

			final String finalUserId = userId;
			accessor.setUser(new Principal() {

				@Override
				public String getName() {
					return finalUserId;
				}
			});

		} else if (StompCommand.SUBSCRIBE.equals(accessor.getCommand())) {
		} else if (StompCommand.SEND.equals(accessor.getCommand())) {
		}
		return ChannelInterceptor.super.preSend(message, channel);
	}

	/**
	 * 发送消息到通道后
	 * 
	 * @param message
	 * @param channel
	 * @return
	 */
	@Override
	public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
		ChannelInterceptor.super.postSend(message, channel, sent);
	}

	/**
	 * 发送完成后
	 * 
	 * @param message
	 * @param channel
	 * @return
	 */
	@Override
	public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
		ChannelInterceptor.super.afterSendCompletion(message, channel, sent, ex);
	}

	@Override
	public boolean preReceive(MessageChannel channel) {
		return ChannelInterceptor.super.preReceive(channel);
	}

	@Override
	public Message<?> postReceive(Message<?> message, MessageChannel channel) {
		return ChannelInterceptor.super.postReceive(message, channel);
	}

	@Override
	public void afterReceiveCompletion(Message<?> message, MessageChannel channel, Exception ex) {
		ChannelInterceptor.super.afterReceiveCompletion(message, channel, ex);
	}
}